package com.fram.common.util.tencent;

import java.security.spec.AlgorithmParameterSpec;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * 微信工具类
 */
public class WechatXcxIvUtil {

	public static String decryptData(String encrypted, String sessionKey, String iv) {
		try {
			byte[] encrypData = org.apache.commons.codec.binary.Base64.decodeBase64(encrypted);
			byte[] ivData = org.apache.commons.codec.binary.Base64.decodeBase64(iv);
			byte[] sKey = org.apache.commons.codec.binary.Base64.decodeBase64(sessionKey);
			String decrypt = decrypt(sKey, ivData, encrypData);
			return decrypt;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String decrypt(byte[] key, byte[] iv, byte[] encData) throws Exception {
		AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
		cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
		// 解析解密后的字符串
		return new String(cipher.doFinal(encData), "UTF-8");
	}

	public static void main(String[] args) {
		try {
			System.out.println(decryptData(
					"tOsUjQ1x76FwdOa+/K1zR49K8TwhfIwb16+Y34MD+ZcugfAtlD1Bb6To7KhZt9iO3myTOvcQ5scW+jOa/CnQT4Mz9fH3fdFyTmtVT/DJISafGbmFF1N0jII+9UgIAPizlqoJBxPZ2M5xSYcokEpawoqgP8cXsAjvkj/6WFwEyHWVQkncaLEoWeJSF3PJIA4Ib0QIPIZyQfr2V7tgFMaKBg==",
					"8NJbtsrB1MTklyhdLHeTVw==", "VXds+E4EXJgCc3N7FcjxiQ=="));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}